/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.core.model.objectify;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import lt.ntec.danblog.server.core.model.TagDAO;
import lt.ntec.danblog.server.core.model.Taggable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Tadas
 */
class TagParentListProxy implements InvocationHandler {

    private static final Logger LOG =
            LoggerFactory.getLogger(TagParentListProxy.class);
    private Set<? extends Taggable> parents;
    private final ObjectifyTag oTag;
    private final TagDAO tagDAO;

    public static Set<Taggable> newInstance(ObjectifyTag tag,
                                                      TagDAO tagDAO) {
        return (Set<Taggable>) Proxy.newProxyInstance(
                Set.class.getClassLoader(),
                new Class[]{Set.class},
                new TagParentListProxy(tag, tagDAO));
    }

    private TagParentListProxy(ObjectifyTag oTag, TagDAO tagDAO) {
        this.oTag = oTag;
        this.tagDAO = tagDAO;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {

        if (parents == null) {
            LOG.debug("Creating proxy");
            parents = tagDAO.getParentsByTag(oTag);
        }

        LOG.debug("Delegating call for " + method.getName());

        return method.invoke(parents, args);
    }
}